package com.leslie.hhcommunity.controller;

import com.leslie.hhcommunity.entity.Comment;
import com.leslie.hhcommunity.entity.DiscussPost;
import com.leslie.hhcommunity.entity.Event;
import com.leslie.hhcommunity.entity.User;
import com.leslie.hhcommunity.event.EventProducer;
import com.leslie.hhcommunity.service.CommentService;
import com.leslie.hhcommunity.service.DiscussPostService;
import com.leslie.hhcommunity.util.CommunityConstant;
import com.leslie.hhcommunity.util.HostHolder;
import com.leslie.hhcommunity.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;

/**
 * @author
 * @PackageName:com.leslie.hhcommunity.controller
 * @ClassnName:CommentController
 * @Description:
 * @Date 2022/1/4  12:10
 */
@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {

	@Autowired
	CommentService commentService;
	@Autowired
	HostHolder hostHolder;
	@Autowired
	EventProducer eventProducer;
	@Autowired
	DiscussPostService discussPostService;
	@Autowired
	RedisTemplate redisTemplate;
	/**
	 * 添加评论
	 *
	 * @param discussPostId
	 * @param comment
	 * @return
	 */
	@RequestMapping(value = "/add/{discussPostId}", method = RequestMethod.POST)
	public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment) {
		User user = hostHolder.getUser();
		comment.setUserId(user.getId());
		comment.setStatus(0);
		comment.setCreateTime(new Date());
		commentService.insertComment(comment);

		//触发事件
		Event event = new Event()
				.setTopic(TOPIC_COMMENT)
				.setUserId(comment.getUserId())
				.setEntityType(comment.getEntityType())//隐藏域获取
				.setEntityId(comment.getEntityId())
				.setData("postId", discussPostId);//系统通知，跳转发指定帖子时需要
		if (comment.getEntityType() == ENTITY_TYPE_POST) {//给帖子的评论
			DiscussPost target = discussPostService.selectDiscussPostById(comment.getEntityId());
			event.setEntityUserId(target.getUserId());//帖子的作者id
		} else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {//给评论的评论
			Comment target = commentService.selectCommentsById(comment.getEntityId());
			event.setEntityUserId(target.getUserId());//评论人的id
		}
		eventProducer.fireEvent(event);

		if (comment.getEntityType() == ENTITY_TYPE_POST) {
			//触发发帖事件
			event = new Event()
					.setTopic(TOPIC_PUBLISH)
					.setUserId(comment.getUserId())
					.setEntityType(ENTITY_TYPE_POST)
					.setEntityId(discussPostId);
			eventProducer.fireEvent(event);

			// 计算帖子的分数
			String redisKey = RedisKeyUtil.getPostScoreKey();
			redisTemplate.opsForSet().add(redisKey, discussPostId);
		}

		return "redirect:/discuss/detail/" + discussPostId;
	}
}
